package cn.ldf.keepaccounts.utils;

import cn.ldf.keepaccounts.exception.ServerException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * @author ldf
 * @code May there be no bugs in the world!
 */
public class StreamUtil {

    /**
     * 将流转为为字节数组
     *
     * @param inStream 输入流
     * @return 字节数组
     */
    public static byte[] readInputStream(InputStream inStream) {
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream();) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            return outStream.toByteArray();
        } catch (IOException e) {
            throw new ServerException("文件流读取失败",e);
        }
    }

    /**
     * 将字节数组转换为Base64编码的字符串
     *
     * @param bytes 字节数组，通常来源于文件、图像或其他二进制数据
     * @return 返回Base64编码后的字符串表示形式
     */
    public static String byteToBase64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }
}
